/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.esrz.service.impl;

import me.zhengjie.modules.cspimp.esrz.domain.Jha;
import me.zhengjie.modules.system.domain.AreaManage;
import me.zhengjie.modules.system.repository.AreaManageRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.esrz.repository.JhaRepository;
import me.zhengjie.modules.cspimp.esrz.service.JhaService;
import me.zhengjie.modules.cspimp.esrz.service.dto.JhaDto;
import me.zhengjie.modules.cspimp.esrz.service.dto.JhaQueryCriteria;
import me.zhengjie.modules.cspimp.esrz.service.mapstruct.JhaMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黄星星
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-06-26
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JhaServiceImpl implements JhaService {

    private final JhaRepository jhaRepository;
    private final JhaMapper jhaMapper;
    private final AreaManageRepository areaManageRepository;

    @Override
    public Map<String, Object> queryAll(JhaQueryCriteria criteria, Pageable pageable) {
        Page<Jha> page = jhaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(jhaMapper::toDto));
    }

    @Override
    public List<JhaDto> queryAll(JhaQueryCriteria criteria) {
        return jhaMapper.toDto(jhaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public JhaDto findById(Long id) {
        Jha jha = jhaRepository.findById(id).orElseGet(Jha::new);
        ValidationUtil.isNull(jha.getId(), "Jha", "id", id);
        return jhaMapper.toDto(jha);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JhaDto create(Jha resources) {
        Long areaZoneId = resources.getAreaZoneId();
        if(null != areaZoneId){
            Optional<AreaManage> areaManageOptional = areaManageRepository.findById(areaZoneId);
            if(null != areaManageOptional){
                AreaManage areaManage = areaManageOptional.get();
                if(null != areaManage){
                    resources.setAreaZoneName(areaManage.getAreaName());
                }
            }
        }

        String jhaNumber = resources.getJhaNumber();
        if(StringUtils.isEmpty(jhaNumber)){
            resources.setJhaNumber("默认");
        }

        Long jhaRiskLevelId = resources.getJhaRiskLevelId();
        if(null == jhaRiskLevelId){
            resources.setJhaRiskLevelId(0L);
            resources.setJhaRiskLevelCode("DEFAULT_RISK");
            resources.setJhaRiskLevelName("默认");
        }
        return jhaMapper.toDto(jhaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Jha resources) {
        Jha jha = jhaRepository.findById(resources.getId()).orElseGet(Jha::new);
        ValidationUtil.isNull(jha.getId(), "Jha", "id", resources.getId());
        jha.copy(resources);
        Long areaZoneId = resources.getAreaZoneId();
        String areaZoneName = resources.getAreaZoneName();
        if (null != areaZoneId) {
            Optional<AreaManage> areaManageOptional = areaManageRepository.findById(areaZoneId);
            if (null != areaManageOptional) {
                AreaManage areaManage = areaManageOptional.get();
                if (null != areaManage) {
                    jha.setAreaZoneName(areaManage.getAreaName());
                }
            }
        }

        String jhaNumber = resources.getJhaNumber();
        if (StringUtils.isEmpty(jhaNumber)) {
            jha.setJhaNumber("默认");
        }

        Long jhaRiskLevelId = resources.getJhaRiskLevelId();
        if (null == jhaRiskLevelId) {
            jha.setJhaRiskLevelId(0L);
            jha.setJhaRiskLevelCode("DEFAULT_RISK");
            jha.setJhaRiskLevelName("默认");
        }
        jhaRepository.save(jha);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            jhaRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<JhaDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (JhaDto jha : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("所属公司", jha.getCid());
            map.put("所属项目", jha.getPid());
            map.put("创建时间", jha.getCreateTime());
            map.put("更新时间", jha.getUpdateTime());
            map.put("创建者", jha.getCreateBy());
            map.put("更新者", jha.getUpdateBy());
            map.put("所在分区主键", jha.getAreaZoneId());
            map.put("所在分区名称", jha.getAreaZoneName());
            map.put("所在分区名称", jha.getJhaName());
            map.put("默认数量", jha.getJhaNumber());
            map.put("风险等级主键", jha.getJhaRiskLevelId());
            map.put("风险等级code", jha.getJhaRiskLevelCode());
            map.put("风险等级名称", jha.getJhaRiskLevelName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}